package cn.itbeien.core.util;

import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author beien
 * @date 2024-03-05 11:50
 * Copyright© 2024 beien
 * 负载均衡算法 轮询，随机
 */
@Component
public class LoadBalancer {
    private  List<String> servers = new ArrayList<>();

    private int currentServerIndex = 0;
    /**
     * 轮询算法
     * @return 服务器地址
     */
    public String roundRobin(){
        if (servers.isEmpty()) {
            return null;
        }
        //String server = servers.get(currentServerIndex);
        currentServerIndex = (currentServerIndex + 1) % servers.size();
        return this.servers.get(currentServerIndex);
    }

    /**
     * 随机算法
     * @return
     */
    public Integer random(){
        if (servers.isEmpty()) {
            return null;
        }
        int randomIndex = new Random().nextInt(servers.size());
        return randomIndex;
    }

    public List<String> getServers() {
        return servers;
    }

    public void setServers(List<String> servers) {
        this.servers = servers;
    }

    public static void main(String[] args) {
        List<String> servers = new ArrayList<>();
        servers.add("http://127.0.0.1:8080/");
        servers.add("http://127.0.0.2:8080/");
        servers.add("http://127.0.0.3:8080/");
        servers.add("http://127.0.0.4:8080/");



        for(int i=0;i<=20;i++){
            LoadBalancer loadBalancer =  new LoadBalancer();
            loadBalancer.setServers(servers);
            //int randomIndex = new Random().nextInt(servers.size());
            /*int randomIndex =  loadBalancer.random();
            System.out.println(loadBalancer.getServers().get(randomIndex));
*/
            System.out.println(loadBalancer.roundRobin());
        }
    }
}
